/**
 * 作者：郑强
 * 
 * JS限制输入框输入数字
 * 
 * 使用方法：在对应的输入框上加上 decimal 属性 值为限制输入小数点的位数  值为0，则限制不能输入小数
 * 
 * */

//添加绑定事件
function addEvent(obj,type,fn){
    if(obj.addEventListener){
        obj.addEventListener(type,fn,false);
    }else if(obj.attachEvent){
        obj.attachEvent('on'+type,fn);
    }
}
//初始化
addEvent(window, "load", function(){
	var inputs = document.getElementsByTagName("input");
	for(var i =0;i<inputs.length;i++){
		if(inputs.item(i).hasAttribute("decimal")){
			var decimal = inputs.item(i).getAttribute("decimal");
			if(decimal&&decimal>0){
				inputs.item(i).setAttribute("oninput","__keepFloat(this,"+ decimal +")");
				inputs.item(i).setAttribute("onpropertychange","__keepFloat(this,"+ decimal +")");
				inputs.item(i).setAttribute("onbeforepaste","__keepClipBoardFloat("+ decimal +")");
			}else{
				inputs.item(i).setAttribute("oninput","__keepInt(this)");
				inputs.item(i).setAttribute("onpropertychange","__keepInt(this)");
				inputs.item(i).setAttribute("onbeforepaste","__keepClipBoardInt()");
			}
		}
	}
});
//保持输入框为int类型
function __keepInt(input){
	var value = input.value.replace(/[^\d]/g,'');
	input.value = value;
	if(typeof(input.value) == "undefined"){
		input.value = 1;
	}
	if(input.value==0){
		input.value = 1;
	}
}
//保持输入框为浮点类型
function __keepFloat(input,decimal){
	var value = input.value.replace(/[^\d.]/g,'');
	value = value.replace(/^\./g,"");
	value = value.replace(/\.{2,}/g,".");
	value = value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
	var decimalIndex = value.indexOf(".");
	if(decimalIndex != -1){
		var decimalStart = value.substring(0,decimalIndex);
		var decimalEnd = value.substring(decimalIndex+1);
		if(decimalEnd&&decimalEnd.length > decimal){
			decimalEnd = decimalEnd.substring(0,decimal);
		}
		value = decimalStart + "." + decimalEnd;
	}
	input.value = value;
	if(typeof(input.value) == "undefined"){
		input.value = 1;
	}
	if(input.value==0){
		input.value = 1;
	}
}
//保持剪切板为浮点类型
function __keepClipBoardFloat(decimal){
	var value = clipboardData.getData('text');
	value = value.replace(/[^\d.]/g,'');
	value = value.replace(/^\./g,"");
	value = value.replace(/\.{2,}/g,".");
	value = value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
	var decimalIndex = value.indexOf(".");
	if(decimalIndex != -1){
		var decimalStart = value.substring(0,decimalIndex);
		var decimalEnd = value.substring(decimalIndex+1);
		if(decimalEnd&&decimalEnd.length > decimal){
			decimalEnd = decimalEnd.substring(0,decimal);
		}
		value = decimalStart + "." + decimalEnd;
	}
	clipboardData.setData('text',value)
}
//保持剪切板为int类型
function __keepClipBoardInt(){
	var value = clipboardData.getData('text');
	value = value.replace(/[^\d]/g,'');
	clipboardData.setData('text',value)
}